package com.laboratory.miniolearning.service.impl;

import com.laboratory.miniolearning.domin.FileVO;
import com.laboratory.miniolearning.properties.MinioProperties;
import com.laboratory.miniolearning.service.UploadService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class MinioSysFileServiceImpl implements UploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public FileVO upload(MultipartFile file) {
        log.info("开始上传文件");
        try {
            String originalFilename = file.getOriginalFilename(); // 文件名
            String extname = originalFilename.substring(originalFilename.lastIndexOf(".")); // 文件后缀
            PutObjectArgs args = PutObjectArgs.builder() // 创建上传参数
                    .bucket(minioProperties.getBucket()) // 存储桶
                    .object(originalFilename) // 文件名
                    .stream(file.getInputStream(), file.getSize(), -1) // 文件流
                    .contentType(file.getContentType()) // 文件类型
                    .build(); // 构建上传参数
            minioClient.putObject(args); // 上传文件
            log.info("文件上传成功");
            String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucket() + "/" + originalFilename;
            return new FileVO(url, originalFilename, file.getSize(), extname);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
